
const userManagementController = function(HttpService) {
  'ngInject';

  const vm = this;

  vm.users = [];
  vm.tenants = [];
  vm.isLoading = false;
  vm.showCreateForm = false;
  vm.showEditForm = false;
  vm.currentUser = null;

  vm.filters = {
    role: '',
    department: '',
    tenant: '',
    search: ''
  };

  vm.newUser = {
    username: '',
    password: '',
    email: '',
    name: '',
    employee_id: '',
    department: '',
    role: 'user',
    tenant_id: ''
  };

  vm.roles = [
    { value: 'user', label: '普通用户' },
    { value: 'operator', label: '操作员' },
    { value: 'support', label: '技术支持' },
    { value: 'administrator', label: '管理员' }
  ];

  vm.departments = [];

  // 初始化
  vm.$onInit = function() {
    loadUsers();
    loadTenants();
    loadDepartments();
  };

  function loadUsers() {
    vm.isLoading = true;
    
    const params = {};
    if (vm.filters.role) params.role = vm.filters.role;
    if (vm.filters.department) params.department = vm.filters.department;
    if (vm.filters.tenant) params.tenant_id = vm.filters.tenant;
    if (vm.filters.search) params.search = vm.filters.search;

    HttpService.users.list(params)
      .then(response => {
        if (response.success) {
          vm.users = response.data;
        } else {
          console.error('加载用户列表失败:', response.message);
          alert('加载用户列表失败：' + response.message);
        }
      })
      .catch(error => {
        console.error('加载用户列表失败:', error);
        alert('加载用户列表失败：' + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isLoading = false;
      });
  }

  function loadTenants() {
    HttpService.tenants.list()
      .then(response => {
        if (response.success) {
          vm.tenants = response.data;
        }
      })
      .catch(error => {
        console.error('加载租户列表失败:', error);
      });
  }

  function loadDepartments() {
    HttpService.departments.list({ status: 1 })
      .then(response => {
        if (response.success) {
          vm.departments = response.data.map(dept => dept.name);
        }
      })
      .catch(error => {
        console.error('加载部门列表失败:', error);
        // fallback to default departments if API fails
        vm.departments = [
          'IT部门', '财务部', '人力资源部', '市场营销部', 
          '销售部', '产品研发部', '运营部', '客服部', '行政部', '法务部'
        ];
      });
  }

  vm.searchUsers = function() {
    loadUsers();
  };

  vm.clearFilters = function() {
    vm.filters = {
      role: '',
      department: '',
      tenant: '',
      search: ''
    };
    loadUsers();
  };

  vm.showCreateUserForm = function() {
    vm.showCreateForm = true;
    vm.newUser = {
      username: '',
      password: '',
      email: '',
      name: '',
      employee_id: '',
      department: '',
      role: 'user',
      tenant_id: ''
    };
  };

  vm.hideCreateForm = function() {
    vm.showCreateForm = false;
    if (vm.userForm) {
      vm.userForm.$setPristine();
      vm.userForm.$setUntouched();
    }
  };

  vm.createUser = function() {
    if (vm.userForm.$invalid) {
      alert('请填写必填字段');
      return;
    }

    vm.isLoading = true;

    HttpService.users.create(vm.newUser)
      .then(response => {
        if (response.success) {
          alert('用户创建成功！');
          vm.hideCreateForm();
          loadUsers();
        } else {
          alert('用户创建失败：' + response.message);
        }
      })
      .catch(error => {
        alert('用户创建失败：' + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isLoading = false;
      });
  };

  vm.getRoleText = function(role) {
    const roleMap = {
      'user': '普通用户',
      'operator': '操作员', 
      'support': '技术支持',
      'administrator': '管理员'
    };
    return roleMap[role] || role;
  };

  vm.getRoleBadgeClass = function(role) {
    const classMap = {
      'administrator': 'badge-danger',
      'support': 'badge-warning',
      'operator': 'badge-info',
      'user': 'badge-secondary'
    };
    return classMap[role] || 'badge-secondary';
  };
};

const userManagementComponent = {
  templateUrl: 'src/app/pages/user-management/user-management.template.html',
  controller: userManagementController
};

function initUserManagementController() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化用户管理控制器模块');
    return;
  }

  angular.module('app.pages.userManagement', [])
    .component('userManagementPage', userManagementComponent);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initUserManagementController();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initUserManagementController();
}